package com.cosmic.pizza.web;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    public void service(ServletRequest req, ServletResponse resp){
        //方法的分发
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //通过url路径判断方法名
        String uri = request.getRequestURI();
        String methodName = uri.substring(uri.lastIndexOf("/")+ 1);
        //通过方法名调用方法
        Class cls = this.getClass();
        try {
            Method method = cls.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            method.invoke(this,request,response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    public void writeValue(ServletResponse resp, Object info) throws IOException {
        resp.setContentType("application/json;charset=utf-8");
        new ObjectMapper().writeValue(resp.getWriter(), info);
    }
}
